package com.excilys.formation.project.repository.impl;

import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.excilys.formation.project.entities.Compte;
import com.excilys.formation.project.repository.CompteDAO;

/**
 * 
 * @author excilys
 * 
 */
@Repository
public class CompteDAOImpl implements CompteDAO {
	/**
	 * Entity Manager injecté par Spring.
	 */
	@PersistenceContext
	private EntityManager em;

	@Override
	public Compte getCompte(String numero) {
		return em.find(Compte.class, numero);
	}

	@Override
	public void save(Compte compte) {
		em.persist(em.merge(compte));

	}

	@SuppressWarnings("unchecked")
	@Override
	public SortedSet<Compte> getComptesByClient(long clientId) {
		Query q = em.createQuery("SELECT c FROM Compte c WHERE c.client.id = :id ");
		q.setParameter("id", clientId);
		return new TreeSet<Compte>(q.getResultList());
	}
}
